import 'package:aone_common/common.dart';
import 'package:aone_common/entities/entities.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:prototype/theme/custom_theme.dart';
import 'package:get/get.dart';
import 'package:prototype/views/game_category/game_category_controller.dart';

class ProviderSelector extends StatelessWidget {
  const ProviderSelector({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final state = GameCategoryLogic.to.state;

    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: 10.w,
        vertical: 10.h,
      ),
      color: CustomTheme.colorSchema.tertiary,
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          mainAxisSpacing: 8.h,
          crossAxisSpacing: 10.w,
          childAspectRatio: 0.85,
        ),
        itemCount: state.providers.length,
        itemBuilder: (BuildContext context, int index) {
          SubChildren item = state.providers[index];
          return Material(
            color: Colors.transparent,
            clipBehavior: Clip.antiAlias,
            borderRadius: BorderRadius.circular(8.0),
            child: InkWell(
              onTap: () => _onTapProvider(item),
              child: Obx(
                () {
                  var isActive = state.activeProvider == item.gameTag;
                  return Column(
                    children: [
                      AnimatedOpacity(
                        opacity: isActive ? 1.0 : 0.5,
                        duration: const Duration(milliseconds: 300),
                        child: CachedNetworkImage(
                          fit: BoxFit.fill,
                          imageUrl: _getImgUrl(item.gameTag!),
                        ),
                      ),
                      Text(
                        fieldTranslator(item),
                        style: TextStyle(
                          overflow: TextOverflow.ellipsis,
                          color:
                              isActive ? null : CustomTheme.colorSchema.neutral,
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
          );
        },
      ),
    );
  }

  void _onTapProvider(SubChildren item) {
    final logic = GameCategoryLogic.to;
    final ctrl = GameCategoryController.to;
    logic.onSelectProvider(item);
    ctrl.toggleProviderVisible();
  }

  String _getImgUrl(String tag) {
    final staticUrl = GlobalService.to.state.siteHeaders.necStaticUrl;
    return '$staticUrl/static/comm/gameImage/egame/60-118v6/$tag.png';
  }
}
